import base64
import uuid

from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from rest_framework import serializers
from .models import Canvas

class CanvasSerializer(serializers.ModelSerializer):
    """
    画布详情序列化器，展示所有字段
    """
    project = serializers.CharField(source='project.name', read_only=True)
    class Meta:
        model = Canvas
        fields = '__all__'
        read_only_fields = ['id', 'position', 'created_at', 'updated_at']


class CreateCanvasSerializer(serializers.ModelSerializer):
    """
    创建画布序列化器（增加Base64图片支持）
    """
    background_image_data = serializers.CharField(
        required=False,
        allow_null=True,
        write_only=True,
        help_text="Base64编码的图片数据（示例：...）"
    )

    class Meta:
        model = Canvas
        fields = [
            'project', 'name', 'canvas_size',
            'background', 'original_size', 'background_image_data'
        ]
        extra_kwargs = {
            'project': {'required': True},
            'name': {'required': True},
            'background_image': {'read_only': True}  # 确保该字段不可直接写入
        }

    def validate_background_image_data(self, value):
        """Base64图片解码验证"""
        if not value:
            return None

        try:
            # 拆分数据头
            header, data = value.split(';base64,')

            # 提取MIME类型
            mime_type = header.split(':')[-1]
            if mime_type not in ['image/jpeg', 'image/png']:
                raise serializers.ValidationError("仅支持JPEG/PNG格式")

            # 解码数据
            decoded_file = base64.b64decode(data)

            # 验证文件大小（10MB）
            if len(decoded_file) > 10 * 1024 * 1024:
                raise serializers.ValidationError("文件大小超过10MB")

            return {
                'data': decoded_file,
                'mime_type': mime_type,
                'extension': 'jpg' if 'jpeg' in mime_type else 'png'
            }
        except ValueError:
            raise serializers.ValidationError("无效的Base64格式")
        except Exception as e:
            raise serializers.ValidationError(f"图片解析失败: {str(e)}")

    def create(self, validated_data):
        """处理图片上传"""
        image_data = validated_data.pop('background_image_data', None)

        # 创建基础实例
        instance = super().create(validated_data)

        # 处理图片上传
        if image_data:
            file_name = f"canvas_bg/{instance.project.name}/{instance.name}/{uuid.uuid4()}.{image_data['extension']}"
            file_content = ContentFile(image_data['data'], name=file_name)

            # 使用default_storage保存
            saved_path = default_storage.save(file_name, file_content)
            instance.background_image = saved_path
            instance.save()

        return instance


class BulkCreateCanvasSerializer(CreateCanvasSerializer):
    """
    批量创建画布序列化器（继承自原有序列化器）
    """
    class Meta(CreateCanvasSerializer.Meta):
        pass


class UpdateCanvasSerializer(serializers.ModelSerializer):
    """
    更新画布时使用的序列化器
    """
    class Meta:
        model = Canvas
        # 更新时允许修改的字段
        fields = ['name', 'canvas_size', 'background', 'original_size']
        extra_kwargs = {
            'name': {'required': False},
            'canvas_size': {'required': False},
            'background': {'required': False},
            'original_size': {'required': False},
        }
